<?php
/**
 * websocket 结束事件
 * 用户下线
 */
namespace app\Listener;

use Firebase\JWT\JWT;
use Swostar\Event\Listener;
use Swostar\Server\WebSocket\Connections;
use Swostar\Server\WebSocket\WebSocketServer;

class WsCloseListener extends Listener
{
    protected $name = 'ws.close';

    public function run(WebSocketServer $webSocketServer = null, $server = null, $fd = null)
    {
        // 获取用户的request对象
        $request = Connections::get($fd)['request'];
        $token = $request->header['sec-websocket-protocol'];

        $config = app('config');
        $key = $config->get('server.routeServer.jwt.key');

        // 从token中解析用户信息
        $jwt = JWT::decode($token, $key, $config->get('server.routeServer.jwt.alg'));

        // 删除redis中对应的用户信息
        $webSocketServer->getRedis()->hDel($key, $jwt->data->uid);
    }
}
